package com.itheima.travel.service.impl;

import com.itheima.travel.mapper.UserMapper;
import com.itheima.travel.pojo.User;
import com.itheima.travel.pojo.UserExample;
import com.itheima.travel.req.UserVo;
import com.itheima.travel.service.UserService;
import com.itheima.travel.utils.BeanConv;
import com.itheima.travel.utils.EmptyUtil;
import com.itheima.travel.utils.MD5Coder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private HttpSession httpSession;

    /**
     * 注册方法
     * @param userVo
     * @return
     */
    @Override
    public Boolean registerUser(UserVo userVo) {
        User user = BeanConv.toBean(userVo, User.class);
        user.setPassword(MD5Coder.md5Encode(userVo.getPassword()));
        int falg = userMapper.insert(user);
        return falg>0;
    }

    /**
     * 登录方法
     * @param userVo
     * @return
     */
    @Override
    public UserVo loginUser(UserVo userVo) {

        UserExample example = new UserExample();
        example.createCriteria()
                .andUsernameEqualTo(userVo.getUsername())
                .andPasswordEqualTo(MD5Coder.md5Encode(userVo.getPassword()));
        List<User> userList = userMapper.selectByExample(example);
        if (userList.size()>0){
            String sessionId = httpSession.getId();
            UserVo userVoResult = BeanConv.toBean(userList.get(0), UserVo.class);
            userVoResult.setSessionId(sessionId);
            httpSession.setAttribute(sessionId,userVoResult);
            return userVoResult;
        }
        return null;
    }

    /**
     * 退出登录
     */
    @Override
    public void loginOutUser() {
    httpSession.removeAttribute(httpSession.getId());
    }

    /**
     * 判断是否登录
     * @return
     */
    @Override
    public Boolean isLogin() {
        Object obj = httpSession.getAttribute(httpSession.getId());
        return !EmptyUtil.isNullOrEmpty(obj);
    }
}
